package com.caowei.weicimpress.weicimpress;

import android.content.Context;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.caowei.weicimpress.weicimpress.widget.SearchWindow;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by caoweiPc on 2014/7/16.
 * todo MySearchView 先定制系统的 以后有机会再重写 吧
 */
public class MySearchView extends SearchView implements SearchView.OnQueryTextListener,
        SearchView.OnClickListener,SearchView.OnCloseListener,MainActivity.OnIndicatorOrQueryClick
      {
    private final static String TAG=MySearchView.class.getSimpleName();
    private ActionBar actionBar;
    private ImageView mCloseButton;
    private ActionBarActivity activity;
    private int SCREEN_W;
    private int SCREEN_H;
    private SearchAutoComplete mQueryTextView;
    private SearchWindow searchWindow;
    private View mSubmitButton;
    private ImageView mSearchButton;
    public MySearchView (Context context) {
        this(context, null);
    }

    public MySearchView (Context context,AttributeSet attrs) {
        super(context, attrs);
        activity=ActivityManager.getInstance().peekTop();
        actionBar=activity.getSupportActionBar();
        traversSearchView();
        this.setQueryHint(getResources().getString(R.string.searchfile));
        this.setOnQueryTextListener(this);
        this.setOnSearchClickListener(this);
        this.setOnCloseListener(this);


        SCREEN_H=  activity.getResources().getDisplayMetrics().heightPixels;
        SCREEN_W=  activity.getResources().getDisplayMetrics().widthPixels;


        searchWindow=new SearchWindow(activity);

        searchWindow.setmOnDismissListener(new SearchWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

        searchWindow.setOnAfterCoverTouchListener(new SearchWindow.OnAfterCoverTouchListener() {
            @Override
            public void onAfter() {
                int displayoptions= actionBar.getDisplayOptions()&ActionBar.DISPLAY_HOME_AS_UP;
                if(displayoptions==0){
                    return;
                }
                actionBar.setDisplayHomeAsUpEnabled(false);
                try {
                    Method clearFocusMethod=SearchView.class.getDeclaredMethod("clearFocus");
                    Method updateViewsVisibilityMethod=
                            SearchView.class.getDeclaredMethod("updateViewsVisibility",boolean.class);
                    boolean oldAccessible= clearFocusMethod.isAccessible();
                    if(!oldAccessible){
                        clearFocusMethod.setAccessible(true);
                    }
                    clearFocusMethod.invoke(MySearchView.this);
                    clearFocusMethod.setAccessible(oldAccessible);

                    oldAccessible=updateViewsVisibilityMethod.isAccessible();
                    if(!oldAccessible){
                        updateViewsVisibilityMethod.setAccessible(true);
                    }
                    updateViewsVisibilityMethod.invoke(MySearchView.this,true);
                    updateViewsVisibilityMethod.setAccessible(oldAccessible);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                    throw new MyException(e, MyException.ERROR);
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                    throw new MyException(e, MyException.ERROR);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    throw new MyException(e, MyException.ERROR);
                }
            }
        });

        searchWindow.setSearchClick(new OnClickListener(){
            @Override
            public void onClick(View v) {
                mSubmitButton.performClick();
            }
        });

    }

    private void traversSearchView() {
        try {
            Field field=SearchView.class.getDeclaredField("mSearchButton");
            boolean oldAccessible=field.isAccessible();
            field.setAccessible(true);
            mSearchButton= (ImageView) field.get(this);
            mSearchButton.setImageResource(R.drawable.search);
            field.setAccessible(oldAccessible);

            field=SearchView.class.getDeclaredField("mSearchHintIcon");
            oldAccessible=field.isAccessible();
            field.setAccessible(true);
            ImageView mSearchHintIcon= (ImageView) field.get(this);
            mSearchHintIcon.setImageResource(R.drawable.search);
            field.setAccessible(oldAccessible);

            field=SearchView.class.getDeclaredField("mCloseButton");
            oldAccessible=field.isAccessible();
            field.setAccessible(true);
            mCloseButton= (ImageView) field.get(this);
            mCloseButton.setImageResource(R.drawable.close);
            field.setAccessible(oldAccessible);

            field=SearchView.class.getDeclaredField("mSearchPlate");
            oldAccessible=field.isAccessible();
            field.setAccessible(true);
            LinearLayout mSearchPlate= (LinearLayout) field.get(this);
            mSearchPlate.setBackgroundResource(R.drawable.editbg);
            field.setAccessible(oldAccessible);

            field= SearchView.class.getDeclaredField("mQueryTextView");
            oldAccessible=field.isAccessible();
            field.setAccessible(true);
            mQueryTextView= (SearchAutoComplete) field.get(this);
            mQueryTextView.setTextColor(activity.getResources().getColor(R.color.pure_white));
            field.setAccessible(oldAccessible);

            field=SearchView.class.getDeclaredField("mSubmitButton");
            oldAccessible=field.isAccessible();
            field.setAccessible(true);
            mSubmitButton= (View) field.get(this);
            field.setAccessible(oldAccessible);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            Log.d(TAG,"MySearchView error");
            throw new MyException(e,MyException.ERROR);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            Log.d(TAG,"MySearchView error");
            throw new MyException(e, MyException.ERROR);
        }
    }

    @Override
    public boolean onQueryTextSubmit(String s) {
        final String searchStr=String.valueOf(s);
        int selectIndex= actionBar.getSelectedNavigationIndex();
        final List<FileInfoBean> data;
        final File rootFile;
        final String currentPath;
        if(activity instanceof ActionBarBaseFragment.GetFragment){
            if(selectIndex!=Utils.SYSFRAG_TAB_INDEX&&selectIndex!=Utils.COMPRESSFRAG_TAB_INDEX){
                selectIndex=Utils.SYSFRAG_TAB_INDEX;
            }
            final ActionBarBaseFragment selectedFrgament= (ActionBarBaseFragment) ((BaseFragment.GetFragment)
                    activity).get(selectIndex);
            data=selectedFrgament.getDataResult();
            rootFile=selectedFrgament.getRootFile();
            currentPath=selectedFrgament.findPathPathOnAtionbarLayout().getText().toString();
           if(activity instanceof ActionBarBaseFragment.OnSwitchFragment){

               ((ActionBarBaseFragment.OnSwitchFragment) activity).switchFragment(SearchFragment.class,
                       new BaseFragment.Callback() {
                   @Override
                   public void onCallback(BaseFragment.Callback1 callback) {
                       selectedFrgament.enableFragment(false);
                       searchWindow.dismiss();
                       if(callback!=null){
                           Class cl=((Object)selectedFrgament).getClass();
                           callback.onCallback(cl,searchStr,data,rootFile,currentPath,selectedFrgament);
                       }
                   }
               });
           }
        }
        return true;
    }

    @Override
    public boolean onQueryTextChange(String s) {
         if(!TextUtils.isEmpty(s)){
             searchWindow.showListcontainer(true);
         }else{
             searchWindow.showListcontainer(false);
         }
        String formatedStr=activity.getResources().getString(R.string.searchfile1,s);
        searchWindow.updateListHead(formatedStr);

        if(activity instanceof ActionBarBaseFragment.GetFragment){
            SearchFragment searchFragment = (SearchFragment) ((BaseFragment.GetFragment)
                    activity).get(Utils.SEARCH_TAB_INDEX);
            searchFragment.setSearchStr(s);
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        actionBar.setDisplayHomeAsUpEnabled(true);
        searchWindow.show();
    }

    @Override
    public boolean onClose() {
        return true;
    }

    @Override
    public void onIndicatorClick() {
        int displayoptions= actionBar.getDisplayOptions()&ActionBar.DISPLAY_HOME_AS_UP;
        if(displayoptions==0){
            return;
        }
        actionBar.setDisplayHomeAsUpEnabled(false);
        try {
            Method clearFocusMethod=SearchView.class.getDeclaredMethod("clearFocus");
            Method updateViewsVisibilityMethod=
                    SearchView.class.getDeclaredMethod("updateViewsVisibility",boolean.class);
            boolean oldAccessible= clearFocusMethod.isAccessible();
            if(!oldAccessible){
                clearFocusMethod.setAccessible(true);
            }
            clearFocusMethod.invoke(this);
            clearFocusMethod.setAccessible(oldAccessible);

            oldAccessible=updateViewsVisibilityMethod.isAccessible();
            if(!oldAccessible){
                updateViewsVisibilityMethod.setAccessible(true);
            }
            updateViewsVisibilityMethod.invoke(this,true);
            updateViewsVisibilityMethod.setAccessible(oldAccessible);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            throw new MyException(e,MyException.ERROR);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            throw new MyException(e, MyException.ERROR);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new MyException(e, MyException.ERROR);
        }
        searchWindow.dismiss();
        SearchFragment searchFragment = (SearchFragment) ((BaseFragment.GetFragment)
                activity).get(Utils.SEARCH_TAB_INDEX);
       ActionBarBaseFragment  selectedFrgament=searchFragment.getSelectedFrgament();

        if(selectedFrgament==null){
            int selectTabIndex= actionBar.getSelectedNavigationIndex();
            if(selectTabIndex!=Utils.COMPRESSFRAG_TAB_INDEX&&
                    selectTabIndex!=Utils.SYSFRAG_TAB_INDEX){
                selectedFrgament= (ActionBarBaseFragment)
                        ((ActionBarBaseFragment.GetFragment)activity).get(Utils.SYSFRAG_TAB_INDEX);
            }else{
                return;
            }
        }
        final ActionBarBaseFragment selectedFrgament1=selectedFrgament;
        if(selectedFrgament instanceof ActionBarBaseFragment) {
            Class cl = ((Object) selectedFrgament).getClass();
            ((ActionBarBaseFragment.OnSwitchFragment) activity).switchFragment(cl,
                    new BaseFragment.Callback() {
                        @Override
                        public void onCallback(BaseFragment.Callback1 callback) {
                           if(selectedFrgament1 instanceof SysFileFragment){
                               actionBar.setSelectedNavigationItem(Utils.SYSFRAG_TAB_INDEX);
                           }else if(selectedFrgament1 instanceof CompressFileFragment){
                               actionBar.setSelectedNavigationItem(Utils.COMPRESSFRAG_TAB_INDEX);
                           }
                        }
                    }
            );
        }
    }

      @Override
      public void onSearchBtnClick() {
          int displayoptions= actionBar.getDisplayOptions()&ActionBar.DISPLAY_HOME_AS_UP;
          if(displayoptions!=0){
              return;
          }
          if(mSearchButton!=null){
              mSearchButton.performClick();
              searchWindow.dismiss();
          }
      }

          @Override
          public void onRebackActionbar() {
              int displayoptions= actionBar.getDisplayOptions()&ActionBar.DISPLAY_HOME_AS_UP;
              if(displayoptions==0){
                  return;
              }
              actionBar.setDisplayHomeAsUpEnabled(false);
              try {
                  Method clearFocusMethod=SearchView.class.getDeclaredMethod("clearFocus");
                  Method updateViewsVisibilityMethod=
                          SearchView.class.getDeclaredMethod("updateViewsVisibility",boolean.class);
                  boolean oldAccessible= clearFocusMethod.isAccessible();
                  if(!oldAccessible){
                      clearFocusMethod.setAccessible(true);
                  }
                  clearFocusMethod.invoke(this);
                  clearFocusMethod.setAccessible(oldAccessible);

                  oldAccessible=updateViewsVisibilityMethod.isAccessible();
                  if(!oldAccessible){
                      updateViewsVisibilityMethod.setAccessible(true);
                  }
                  updateViewsVisibilityMethod.invoke(this,true);
                  updateViewsVisibilityMethod.setAccessible(oldAccessible);
              } catch (NoSuchMethodException e) {
                  e.printStackTrace();
                  throw new MyException(e, MyException.ERROR);
              } catch (InvocationTargetException e) {
                  e.printStackTrace();
                  throw new MyException(e, MyException.ERROR);
              } catch (IllegalAccessException e) {
                  e.printStackTrace();
                  throw new MyException(e, MyException.ERROR);
              }
          }

          @Override
          public void onHideSearchBtn(boolean hide) {
              if(mSearchButton.isShown()&&hide){
                  mSearchButton.setVisibility(GONE);
              }else if(!mSearchButton.isShown()&&!hide){
                  mSearchButton.setVisibility(VISIBLE);
              }

          }

      }
